package cn.wlj.origin.work;

import cn.wlj.origin.ConnectUtil;
import cn.wlj.origin.Constant;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;

/**
 * @ClassName Receiver1
 * @Description TODO
 * @Author WLJ
 * @Date 2024/1/11 20:25
 * @Version 1.0
 */
public class Receiver1 {
    public static void main(String[] args) throws Exception {
        // 队列名
        String queueName = Constant.Work.QUEUE_NAME;

        // 获取连接
        Connection connection = ConnectUtil.getConnection();
        // 获取通道
        Channel channel = connection.createChannel();
        // 声明队列
        channel.queueDeclare(queueName, false, false, true, null);
        // 设置每个消费者每次只能处理一条消息，不然会轮休
        channel.basicQos(1);
        // 接收的回调函数
        DeliverCallback deliverCallback = ((s, delivery) ->{
            //接收消息的处理逻辑
            String msg = new String(delivery.getBody(),"UTF-8");
            System.out.println("消费者【1】接收到消息："+msg);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        });
        // 接收错误的回调
        CancelCallback cancelCallback = (s -> {
            System.out.println("消费者【1】接收消息异常");
        });
        channel.basicConsume(queueName, deliverCallback, cancelCallback);
    }
}
